using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.IdentityModel.Tokens.Jwt;

namespace MvcClient
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            // 关闭JWT Claim类型映射，以允许常用的Claim（例如'sub'和'idp'）通过
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(options =>
            {
                // 默认使用Cookies方案进行认证
                // options.DefaultScheme = "Cookies";
                // 默认认证失败时启用oidc方案
                options.DefaultChallengeScheme = "oidc";
            })
            // 添加Cookies认证方案
            .AddCookie("Cookies")
            // 添加oidc方案
            .AddOpenIdConnect("oidc", options =>
            {
                // 身份验证成功后使用Cookies方案来保存信息
                options.SignInScheme = "Cookies";
                // 授权服务地址
                options.Authority = "http://localhost:8888";
                options.RequireHttpsMetadata = false;
                options.ClientId = "mvc_implicit";
                // 默认只返回id_token 这里添加上token(Access Token)
                options.ResponseType = "id_token token";
                options.SaveTokens = true;
            });
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.Lax;
            });
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}